﻿Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.Security.Cryptography
Imports System.Text
Imports log4net
Imports log4net.Config

Partial Class LoginFormTest
    Inherits System.Web.UI.Page
    Dim initLDAPPath As String
    Dim initLDAPServer As String
    Dim initShortDomainName As String
    Dim usname As String
    Dim pwd As String
    Dim strErrMsg As String
    Dim logger As log4net.ILog
    Dim ccerror As Boolean
    Public Function MD5(ByVal strString As String) As String
        Dim ASCIIenc As New ASCIIEncoding
        Dim strReturn As String
        Dim ByteSourceText() As Byte = ASCIIenc.GetBytes(strString)
        Dim Md5Hash As New MD5CryptoServiceProvider
        Dim ByteHash() As Byte = Md5Hash.ComputeHash(ByteSourceText)

        strReturn = ""

        For Each b As Byte In ByteHash
            strReturn = strReturn & b.ToString("x2")
        Next

        Return strReturn

    End Function

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim mode As Integer
        mode = 0
        mode = Val(ConfigurationManager.AppSettings("authenmode"))
        Dim planyear As Integer
        Session.Remove("PlanYear")
        Session.Remove("CMMT_OT_CODE")
        Session.Remove("CMMT_TR_CODE")

        Dim planYearSession As String = ""
        Dim CMMT_OT_CODE As String = ""
        Dim CMMT_TR_CODE As String = ""

        Dim adap As New DBdataTableAdapters.AppConfigsTableAdapter
        Dim dt As New DBdata.AppConfigsDataTable
        dt = adap.GetData
        For Each item As DBdata.AppConfigsRow In dt
            Select Case item.Name
                Case "ACTIVE_PLAN_YEAR"
                    planYearSession = item.Value
                Case "CMMT_OT_CODE"
                    CMMT_OT_CODE = item.Value
                Case "CMMT_TR_CODE"
                    CMMT_TR_CODE = item.Value
            End Select
        Next

        Session.Add("PlanYear", planYearSession)
        Session.Add("CMMT_OT_CODE", CMMT_OT_CODE)
        Session.Add("CMMT_TR_CODE", CMMT_TR_CODE)

        'Session.Add("PlanYear", "2014")
        'Session.Add("CMMT_OT_CODE", "52050050")
        'Session.Add("CMMT_TR_CODE", "52200060")
        planyear = planYearSession 'Edit By Orn 05/08/2558

        'Try
        '    Dim adap As New DBdataTableAdapters.AppConfigsTableAdapter
        '    Dim dt As New DBdata.AppConfigsDataTable
        '    dt = adap.GetData
        '    For Each item As DBdata.AppConfigsRow In dt
        '        Select Case item.Name
        '            Case "ACTIVE_PLAN_YEAR"
        '                Session.Add("PlanYear", item.Value)
        '                planyear = Val(item.Value)
        '            Case "CMMT_OT_CODE"
        '                Session.Add("CMMT_OT_CODE", item.Value)
        '            Case "CMMT_TR_CODE"
        '                Session.Add("CMMT_TR_CODE", item.Value)
        '        End Select
        '    Next
        'Catch ex As Exception

        'End Try

        Dim costcentercode As String = ""

        lbDisplay.Visible = False
        strErrMsg = ""
        ' ''''เข้าระบบด้วย AD
        'Dim DomainAndUsername As String = ""
        'Dim strCommu As String
        'Dim flgLogin As Boolean = False
        'strCommu = "LDAP://" & initLDAPServer & "/" & initLDAPPath
        'DomainAndUsername = initShortDomainName & "\" & txtUser.Text.Trim

        ''Dim entry As New DirectoryEntry(strCommu, DomainAndUsername, txtPwd.Text)
        'Dim entry As New DirectoryEntry(strCommu, usname, pwd)
        'Dim obj As Object

        'Dim f_adapter As New LoginDSTableAdapters.LoginLockTableAdapter
        'Dim f_datatable As New LoginDS.LoginLockDataTable

        'Try
        '    obj = entry.NativeObject
        '    Dim search As New DirectorySearcher(entry)
        '    Dim result As SearchResult
        '    search.Filter = "(SAMAccountName=" + txtUser.Text.Trim + ")"
        '    'search.Filter = "(userPrincipalName=" + txtUser.Text + "@gsberpdev.local)"
        '    'search.PropertiesToLoad.Add("*")
        '    search.PropertiesToLoad.AddRange(New String() {"cn", "postalcode", "employeeid"})
        '    result = search.FindOne()
        '    For Each prop As DictionaryEntry In result.Properties
        '        For Each inval As Object In prop.Value
        '            If prop.Key.ToString = "postalcode" Then
        '                'Response.Write(prop.Key & " = " & inval & "<br />")
        '                'GenCodeCenter(txtUser.Text.Trim, inval.ToString.Trim, planyear)
        '                costcentercode = inval.ToString.Trim
        '            End If
        '        Next
        '    Next
        '    'Exit Sub
        '    If result Is Nothing Then
        '        flgLogin = False
        '        strErrMsg = "กรุณาตรวจสอบ ชื่อผู้ใช้งาน"
        '    Else



        '        Dim pc As New PrincipalContext(ContextType.Domain, initLDAPServer, initLDAPPath)
        '        Dim isvalid As Boolean = pc.ValidateCredentials(txtUser.Text.Trim, txtPwd.Text.Trim)
        '        If isvalid = True Then
        '            Dim check As Integer = 0
        '            Dim usadap As New UserDSTableAdapters.UsersTableAdapter
        '            If mode = 1 Then
        '                f_datatable = f_adapter.GetDataByUser(txtUser.Text.Trim)
        '            End If

        '            check = usadap.CheckUserName(txtUser.Text.Trim)
        '            For Each row As LoginDS.LoginLockRow In f_datatable
        '                Dim sec_diff As Integer
        '                sec_diff = DateDiff(DateInterval.Second, row.LockDate, Now())
        '                If sec_diff < 180 Then
        '                    Dim min, sec As Integer
        '                    min = Math.DivRem((600 - sec_diff), 60, sec)
        '                    Me.lbDisplay.Text = "Userนี้ถูกระงับการใช้บริการชั่วคราว จะใช้บริการได้อีกใน " & min & " นาที " & sec & " วินาที"
        '                    lbDisplay.Visible = True
        '                    txtUser.Text = ""
        '                    txtPwd.Text = ""
        '                    Exit Sub
        '                End If
        '            Next

        '            If check > 0 Then
        '                If mode = 1 Then
        '                    Session("LoginFail") = 0
        '                    Dim adapter As New LoginDSTableAdapters.LoginLogTableAdapter
        '                    Dim exist As Integer
        '                    exist = adapter.CheckExistUser(txtUser.Text.Trim)
        '                    If exist <> 0 Then

        '                        Me.lbDisplay.Text = "User นี้มีการ Login อยู่แล้ว ไม่สามารถทำการ Login ซ้อนได้"
        '                        lbDisplay.Visible = True
        '                        txtUser.Text = ""
        '                        txtPwd.Text = ""
        '                        Exit Sub
        '                    End If
        '                End If


        '                flgLogin = True
        '                Session.Remove("users")
        '                Session.Add("users", txtUser.Text)
        '            Else
        '                flgLogin = False
        '                strErrMsg = "กรุณาตรวจสอบ  ชื่อผู้ใช้งาน"
        '            End If
        '        Else
        '            flgLogin = False
        '            strErrMsg = "กรุณาตรวจสอบ รหัสผ่าน"
        '        End If


        '    End If



        'Catch ex As Exception
        '    flgLogin = False
        '    strErrMsg = "ไม่สามารถเข้าสู่ระบบได้กรุณาติดต่อผู้ดูแลระบบ"
        '    'strErrMsg = ex.ToString
        'End Try

        ''เข้าระบบด้วย user ใน sql

        Dim usadap As New UserDSTableAdapters.UsersTableAdapter
        Dim check As Integer = 0
        Dim flgLogin As Boolean = False
        Dim f_adapter As New LoginDSTableAdapters.LoginLockTableAdapter
        Dim f_datatable As New LoginDS.LoginLockDataTable

        Try
            If mode = 1 Then
                f_datatable = f_adapter.GetDataByUser(txtUser.Text.Trim)
            End If
            check = usadap.CheckUserName(txtUser.Text.Trim)
            'For Each row As LoginDS.LoginLockRow In f_datatable
            '    Dim sec_diff As Integer
            '    sec_diff = DateDiff(DateInterval.Second, row.LockDate, Now())
            '    If sec_diff < 180 Then
            '        Dim min, sec As Integer
            '        min = Math.DivRem((600 - sec_diff), 60, sec)
            '        Me.lbDisplay.Text = "User นี้ถูกระงับการใช้บริการชั่วคราว จะใช้บริการได้อีกใน " & min & " นาที " & sec & " วินาที"
            '        lbDisplay.Visible = True
            '        txtUser.Text = ""
            '        txtPwd.Text = ""
            '        Exit Sub
            '    End If
            'Next
            'If txtUser.Text.Trim <> "bb0011" Then
            '    check = 0
            'End If
            If check > 0 Then
                If mode = 1 Then
                    Session("LoginFail") = 0
                    Dim adapter As New LoginDSTableAdapters.LoginLogTableAdapter
                    Dim exist As Integer
                    exist = adapter.CheckExistUser(txtUser.Text.Trim)
                    If exist <> 0 Then

                        Me.lbDisplay.Text = "User นี้มีการ Login อยู่แล้ว ไม่สามารถทำการ Login ซ้อนได้"
                        lbDisplay.Visible = True
                        txtUser.Text = ""
                        txtPwd.Text = ""
                        Exit Sub
                    End If
                End If

                flgLogin = True
                Session.Remove("users")
                Session.Add("users", txtUser.Text)

                costcentercode = txtUser.Text.Substring(2)
            Else
                flgLogin = False
                strErrMsg = "กรุณาตรวจสอบ ชื่อผู้ใช้งาน/รหัสผ่าน"
            End If
        Catch ex As Exception
            flgLogin = False
            strErrMsg = "กรุณาตรวจสอบ ชื่อผู้ใช้งาน/รหัสผ่าน"
            'strErrMsg = ex.ToString
        End Try

        '' เมื่อ Authen ผ่าน
        If flgLogin = True Then

            Dim rladap As New LoginDSTableAdapters.UsersTableAdapter
            Dim rtype As String = ""
            Dim approve As String = "True"
            rtype = rladap.GetRoleType(txtUser.Text.Trim)
            Select Case rtype
                Case "A"
                    rtype = "1"
                    approve = "False"
                Case "B"
                    rtype = "2"
                    approve = "False"
                Case "C"
                    rtype = "3"
                    approve = "False"
                Case "D"
                    rtype = "4"
                    approve = "False"
                Case "E"
                    rtype = "5"
                    approve = "False"
                Case Else
                    rtype = rtype
                    approve = "True"
            End Select
            'approve = "True"
            Session.Remove("RoleType")
            Session.Add("RoleType", rtype)
            Session.Remove("RoleApprove")
            Session.Add("RoleApprove", approve)


            ' Add By Orn 4/12/2557
            If rtype <> "1" Then '1 = Admin
                Dim appadap As New LoginDSTableAdapters.AppConfigsTableAdapter
                Dim appdt = New LoginDS.AppConfigsDataTable
                appdt = appadap.GetData("TEMPORARY_CLOSE")
                If appdt.Rows.Count > 0 Then
                    If appdt.Rows(0)("Value") = "Y" Then 'N=Open, Y=Close
                        txtUser.Text = ""
                        txtPwd.Text = ""
                        Me.lbDisplay.Text = "ระบบปิดทำการชั่วคราว กรุณาติดต่อผู้ดูแลระบบ"
                        lbDisplay.Visible = True
                        Exit Sub
                    End If
                End If
            End If
            ' End Add By Orn


            ' Add By Garn 10/12/2557
            Session.Remove("EnableAllReport")
            Dim userAdapter As New MasterDataSetTableAdapters.UsersTableAdapter
            Dim checkEnableAllReport As Integer = 0
            checkEnableAllReport = userAdapter.CheckEnableAllReport(Session("users"))
            If checkEnableAllReport > 0 Then
                Session.Add("EnableAllReport", True)
            Else
                Session.Add("EnableAllReport", False)
            End If
            ' End Add By Garn 

            Me.lbDisplay.Text = "ยินดีต้อนรับ " & txtUser.Text + strErrMsg
            lbDisplay.Visible = True

            Try
                FctrGenClass.GenFctrView(txtUser.Text.Trim, planyear)

                If costcentercode.Trim <> "" Then
                    GenCodeCenter(txtUser.Text.Trim, costcentercode, planyear)
                End If

            Catch ex As Exception

            End Try

            'Dim rladap As New LoginDSTableAdapters.UsersTableAdapter
            'Dim rtype As String = ""
            'Dim approve As String = "True"
            'rtype = rladap.GetRoleType(txtUser.Text.Trim)
            'Select Case rtype
            '    Case "A"
            '        rtype = "1"
            '        approve = "False"
            '    Case "B"
            '        rtype = "2"
            '        approve = "False"
            '    Case "C"
            '        rtype = "3"
            '        approve = "False"
            '    Case "D"
            '        rtype = "4"
            '        approve = "False"
            '    Case "E"
            '        rtype = "5"
            '        approve = "False"
            '    Case Else
            '        rtype = rtype
            '        approve = "True"
            'End Select
            'approve = "True"
            'Session.Remove("RoleType")
            'Session.Add("RoleType", rtype)
            'Session.Remove("RoleApprove")
            'Session.Add("RoleApprove", approve)

            Dim adapter As New LoginDSTableAdapters.LoginLogTableAdapter
            adapter.InsertQuery(Session("users"), Session.SessionID)
            logger = log4net.LogManager.GetLogger(Me.GetType)
            logger.Info("Login User: " & Session("users") & "  IP: " & GetClientIP() & "  coscenter: " & costcentercode)

            If ccerror = True Then
                Response.Redirect("Default.aspx?ccerror=1")
            Else
                Response.Redirect("Default.aspx")
            End If

        Else
            If mode = 1 Then
                Session("LoginFail") += 1


                If Session("LoginFail") >= 5 Then

                    f_adapter.InsertQuery(txtUser.Text, Now())
                    Me.lbDisplay.Text = "Login ผิดพลาดติดต่อกัน 5 ครั้ง Userนี้ถูกระงับการใช้งานเป็นเวลา 10 นาที"
                    lbDisplay.Visible = True
                    Exit Sub
                End If
            End If


            txtUser.Text = ""
            txtPwd.Text = ""
            Me.lbDisplay.Text = strErrMsg
            lbDisplay.Visible = True
        End If
    End Sub

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

        Try
            'Local
            'initLDAPPath = "dc=gsberpdev,dc=local"
            'initLDAPServer = "10.251.110.50"
            'initShortDomainName = "gsberpdev"
            'usname = "gsberpdev\erpbindusr"
            'pwd = "password@1234*"

            'Server
            initLDAPPath = ConfigurationManager.AppSettings("initLDAPPath")
            initLDAPServer = ConfigurationManager.AppSettings("initLDAPServer")
            initShortDomainName = ConfigurationManager.AppSettings("initShortDomainName")
            usname = ConfigurationManager.AppSettings("initLDAPusname")
            pwd = ConfigurationManager.AppSettings("initLDAPpwd")
            code_version.InnerText = ConfigurationManager.AppSettings("appVersion")
        Catch ex As Exception

        End Try

        If IsPostBack = False Then
            If Val(Request("logout")) = 1 Then
                logger = Nothing
                logger = log4net.LogManager.GetLogger(Me.GetType)
                logger.Info("Logout User: " & Session("users") & "  IP: " & GetClientIP())
                Session.Remove("users")
                Session.Abandon()
            End If
            Dim adapter As New LoginDSTableAdapters.LoginLogTableAdapter
            adapter.DeleteQuery(Session.SessionID)
        End If

    End Sub

    Function GetClientIP() As String
        Dim currentRequest As HttpRequest = HttpContext.Current.Request
        Dim ipAddress As String = currentRequest.ServerVariables("HTTP_X_FORWARDED_FOR")

        If ipAddress Is Nothing OrElse ipAddress.ToLower() = "unknown" Then
            ipAddress = currentRequest.ServerVariables("REMOTE_ADDR")
        End If

        Return ipAddress
    End Function

    Sub GenCodeCenter(ByVal users As String, ByVal costcenter As String, ByVal planyear As Integer)
        Dim user_name As String = ""
        user_name = users

        Dim ccadap As New CostCenterTableAdapters.CostCentersTableAdapter
        Dim ccdt As New CostCenter.CostCentersDataTable
        ccdt = ccadap.GetDataByCCode(costcenter, planyear)
        If ccdt.Count = 0 Then
            ccerror = True
        End If

        'Dim usfadp As New CostCenterTableAdapters.UserFundCentersTableAdapter
        Dim fcadap As New fctrDSTableAdapters.fctr_viewTableAdapter

        Dim childadap As New LoginDSTableAdapters.Fcth2TableAdapter
        Dim childdt As New LoginDS.Fcth2DataTable
        Dim check As Integer = 0
        For Each item As CostCenter.CostCentersRow In ccdt
            'check = usfadp.CheckExist(planyear, user_name, item.FundCenter_FundCenterCode, item.FundCenter_FundCenterCode)
            'If check = 0 Then
            'usfadp.InsertUSF(planyear, Date.Now, user_name, user_name, item.FundCenter_FundCenterCode, item.FundCenter_PlanYear, item.FundCenter_FundCenterCode, item.FundCenter_PlanYear)
            ' End If

            Dim chk0 As Integer
            chk0 = fcadap.CheckExist(item.FundCenter_FundCenterCode, user_name, planyear)
            If chk0 = 0 Then
                fcadap.Insert(Nothing, item.FundCenter_FundCenterCode, user_name, item.FundCenter_FundCenterCode, planyear)
            End If
            childdt = childadap.GetData(item.FundCenter_FundCenterCode, planyear)
            For Each item2 As LoginDS.Fcth2Row In childdt
                Dim chk As Integer
                chk = fcadap.CheckExist(item2.FundCenter_FundCenterCode, user_name, planyear)
                If chk = 0 Then
                    fcadap.Insert(Nothing, item2.FundCenter_FundCenterCode, user_name, item2.parentcode, planyear)
                End If

            Next
        Next

    End Sub

End Class


